//package com.itstyle.seckill.util.statusflow;
//
//import cn.gogpay.dcb.common.dto.ResultCode;
//import cn.gogpay.dcb.common2.result.ResultDTO;
//import cn.gogpay.dcb.mall.common.constant.MQConstants;
//import cn.gogpay.dcb.mall.common.dto.OrderStandingBookSyncDTO;
//import cn.gogpay.dcb.mall.common.enums.order.OrderTypeEnum;
//import cn.gogpay.dcb.mall.common.enums.order.SettlementStatusEnum;
//import cn.gogpay.dcb.mall.common.enums.saleafter.SaleAfterStatusEnum;
//import cn.gogpay.dcb.mall.order.admin.form.OrderNoForm;
//import cn.gogpay.dcb.mall.order.admin.service.SettlementOrderService;
//import cn.gogpay.dcb.mall.order.dao.OrderCommodityRepository;
//import cn.gogpay.dcb.mall.order.dao.OrderConfigRepository;
//import cn.gogpay.dcb.mall.order.dao.OrderInvoiceRepository;
//import cn.gogpay.dcb.mall.order.entity.*;
//import cn.gogpay.dcb.mall.order.mq.form.UpdateIncomeDistributionRecordBillableStatusForm;
//import cn.gogpay.dcb.mall.order.web.flow.dto.IVoid;
//import cn.gogpay.dcb.mall.order.web.flow.dto.OrderStatusFlux;
//import cn.gogpay.dcb.mall.order.web.flow.form.PayedParams;
//import cn.gogpay.dcb.mall.order.web.service.MallTransactionalService;
//import cn.gogpay.dcb.mall.order.web.service.OrderIncentiveService;
//import cn.gogpay.dcb.mall.order.web.service.OrderInvoiceService;
//import cn.gogpay.dcb.mall.order.web.service.OrderStockService;
//import cn.gogpay.dcb.trade.common.dto.CancelOrderNotifyDTO;
//import cn.gogpay.dcb.trade.common.form.PreOrderForm;
//import com.alibaba.fastjson.JSON;
//import com.querydsl.jpa.impl.JPAQueryFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Optional;
//import java.util.concurrent.CompletableFuture;
//import java.util.concurrent.Executor;
//
///**
// * 标准虚拟订单状态服务类
// *
// * @author chenglong@gogpay.cn
// * @date 2021年8月9日, 0009
// */
//@MallOrderMachine(OrderClassificationEnum.VIRTUAL)
//public class VirtualOrderStatusService {
//    private Logger logger = LoggerFactory.getLogger(getClass());
//
//    /**
//     * 响应订单支付事件
//     *
//     * @param form
//     * @return
//     */
//    @Transactional(rollbackFor = Exception.class)
//    @OnOrderStatusEvent(value = OrderStatusEvent.PAYED, behindStatus = {OrderStatusEnum.WAIT_PAY, OrderStatusEnum.INIT})
//    public ResultDTO<Void> payed(OrderStatusFlux<PayedParams> form) {
//        OrderEntity order = form.getOrderEntity();
//        OrderConfigEntity orderConfig = orderConfigRepository.findByOrderNo(form.getOrderNo());
//        if (orderConfig == null) {
//            return ResultDTO.failure("订单信息不存在");
//        }
//        mallTransactionalService.newTransaction(() -> {
//            QOrderEntity qOrder = QOrderEntity.orderEntity;
//            jpaQueryFactory.update(qOrder)
//                    .set(qOrder.orderStatus, OrderStatusEnum.DONE)
//                    .set(qOrder.payTime, form.getEventSource().getPayTime())
//                    .set(qOrder.reason, form.getReason().getReason(form.getReasonSlots()))
//                    .set(qOrder.payType, form.getEventSource().getPayType())
//                    .set(qOrder.paySerialNo, form.getEventSource().getPaySerialNo())
//                    .set(qOrder.evaluateStatus, 1)
//                    .where(
//                            qOrder.orderNo.eq(form.getOrderNo())
//                    ).execute();
//        });
//        orderIncentiveService.sendIncentive(form.getOrderNo());
//        List<OrderCommodityEntity> orderCommodityEntities = orderCommodityRepository.findAllByOrderNo(order.getOrderNo());
//        OrderInvoiceEntity orderInvoice = orderInvoiceRepository.findByOrderNo(order.getOrderNo());
//        if (orderInvoice != null) {
//            orderInvoice.setPayTime(form.getEventSource().getPayTime());
//            orderInvoiceRepository.saveAndFlush(orderInvoice);
//        }
//
//        List<OrderStandingBookSyncDTO> orderStandingBookSyncDTOList = new ArrayList<>(orderCommodityEntities.size());
//        for (OrderCommodityEntity orderCommodityEntity : orderCommodityEntities) {
//            OrderStandingBookSyncDTO orderStandingBookSyncDTO = new OrderStandingBookSyncDTO();
//            orderStandingBookSyncDTO.setActualReceivable(order.getActualReceivable());
//            orderStandingBookSyncDTO.setCommodityCategoryName(orderCommodityEntity.getCommodityCategoryName());
//            orderStandingBookSyncDTO.setCommodityDiscountAmount(orderCommodityEntity.getDiscountAmount());
//            orderStandingBookSyncDTO.setCommodityName(orderCommodityEntity.getCommodityName());
//            orderStandingBookSyncDTO.setCommodityQuantity(order.getCommodityQuantity());
//            orderStandingBookSyncDTO.setCommodityUnitPrice(orderCommodityEntity.getUnitPrice());
//            orderStandingBookSyncDTO.setDcbUserId(order.getDcbUserId());
//            orderStandingBookSyncDTO.setInvoiceFlag(order.getInvoiceFlag());
//            orderStandingBookSyncDTO.setMarketingType(order.getMarketingType());
//            orderStandingBookSyncDTO.setMerchantName(order.getMerchantName());
//            orderStandingBookSyncDTO.setUserTel(order.getUserTel());
//            orderStandingBookSyncDTO.setTotalPrice(order.getTotalPrice());
//            orderStandingBookSyncDTO.setTotalQuantity(order.getCommodityQuantity());
//            orderStandingBookSyncDTO.setSaleType(order.getSaleType());
//            orderStandingBookSyncDTO.setRefSkuId(orderCommodityEntity.getRefSkuId());
//            orderStandingBookSyncDTO.setRefMerchantId(order.getRefMerchantId());
//            orderStandingBookSyncDTO.setRefMartId(order.getRefMartId());
//            orderStandingBookSyncDTO.setRefCommodityId(orderCommodityEntity.getRefCommodityId());
//            orderStandingBookSyncDTO.setProfitAmount(order.getDistributionProfitAmount());
//            orderStandingBookSyncDTO.setPostFee(order.getPostFee());
//            orderStandingBookSyncDTO.setPayType(form.getEventSource().getPayType());
//            orderStandingBookSyncDTO.setPayTime(form.getEventSource().getPayTime());
//            orderStandingBookSyncDTO.setPaySerialNo(form.getEventSource().getPaySerialNo());
//            orderStandingBookSyncDTO.setParentOrderId(order.getParentOrderId());
//            orderStandingBookSyncDTO.setOrderNo(order.getOrderNo());
//            orderStandingBookSyncDTO.setOrderType(order.getOrderType());
//            orderStandingBookSyncDTO.setOrderDate(order.getOrderDate());
//            orderStandingBookSyncDTOList.add(orderStandingBookSyncDTO);
//
//        }
//        rabbitTemplate.convertAndSend(MQConstants.ORDER_STANDING_BOOK_SYNC_ORDER_INFO_QUEUE,
//                JSON.toJSONString(orderStandingBookSyncDTOList));
//
//        return ResultDTO.success();
//    }
//
//
//    /**
//     * 响应订单关闭事件
//     *
//     * @param form
//     * @return
//     */
//    @Transactional(rollbackFor = Exception.class)
//    @OnOrderStatusEvent(value = OrderStatusEvent.CLOSE, behindStatus = {OrderStatusEnum.WAIT_PAY, OrderStatusEnum.INIT})
//    public ResultDTO<Void> close(OrderStatusFlux<IVoid> form) {
//        OrderEntity order = form.getOrderEntity();
//        OrderNoForm orderNoForm = new OrderNoForm();
//        orderNoForm.setOrderNo(form.getOrderNo());
////        if (order.getOrderStatus() == OrderStatusEnum.WAIT_PAY) {
////            ResultDTO<OrderTradeDTO> checkStatusResult = tradePayClient.checkPayStatus(orderNoForm);
////            logger.info("取消订单检查订单支付状态结果:form={},result={}", orderNoForm, checkStatusResult);
////            if (checkStatusResult.isSuccess()) {
////                PayedParams payedParams = new PayedParams();
////                payedParams.setPaySerialNo(checkStatusResult.getData().getPaySerialNo());
////                payedParams.setPayTime(checkStatusResult.getData().getPayTime());
////                payedParams.setPayType(checkStatusResult.getData().getPayType());
////
////
////                ResultDTO<Void> updateResult = OrderStatusFlux.payedEvent(form.getOrderNo())
////                        .reason(ReasonStatus.PAYED)
////                        .operation("系统")
////                        .eventSource(payedParams)
////                        .start();
////                logger.info("更新订单状态到待发货结果result={}", updateResult);
////                if (!updateResult.isSuccess()) {
////                    return updateResult;
////                }
////                return ResultDTO.failure("订单已支付，请刷新页面");
////            }
////        }
//
//
//        ResultDTO<List<PreOrderForm.SkuInfo>> returnResult = orderStockService.returnStock(form.getOrderNo(), form.getReason());
//        logger.info("取消订单还原库存结果:{}", returnResult);
////        if (!returnResult.isSuccess()) {
////            return ResultDTO.failure(returnResult.getMsg());
////        }
//
//        QOrderEntity qOrder = QOrderEntity.orderEntity;
//        jpaQueryFactory.update(qOrder)
//                .set(qOrder.orderStatus, OrderStatusEnum.CLOSE)
//                .set(qOrder.updateBy, Optional.ofNullable(form.getOperationName()).orElse("系统"))
//                .set(qOrder.reason, form.getReason().getReason(form.getReasonSlots()))
//                .where(
//                        qOrder.orderNo.eq(form.getOrderNo())
//                ).execute();
//
//
//        CancelOrderNotifyDTO cancelOrderNotifyDTO = new CancelOrderNotifyDTO();
//        cancelOrderNotifyDTO.setOrderNo(form.getOrderNo());
//        cancelOrderNotifyDTO.setOrderType(order.getOrderType().getValue());
//        cancelOrderNotifyDTO.setSkuInfo(returnResult.getData());
//        cancelOrderNotifyDTO.setUserId(order.getDcbUserId());
//        if (order.getOrderType() == OrderTypeEnum.SECKILL) {
//            OrderConfigEntity orderConfig = orderConfigRepository.findByOrderNo(order.getOrderNo());
//            cancelOrderNotifyDTO.setActivityId(orderConfig.getRefActivityId());
//        }
//
//        return new ResultDTO<>(ResultCode.tradeSuccess());
//    }
//
//    /**
//     * 响应订单完结事件
//     *
//     * @param form
//     * @return
//     */
//    @Transactional(rollbackFor = Exception.class)
//    @OnOrderStatusEvent(value = OrderStatusEvent.FINISH, behindStatus = {OrderStatusEnum.DONE})
//    public ResultDTO<Void> finish(OrderStatusFlux<IVoid> form) {
//        QOrderCommodityEntity qOrderCommodity = QOrderCommodityEntity.orderCommodityEntity;
//        long saleAfterCount = jpaQueryFactory.selectFrom(qOrderCommodity)
//                .where(qOrderCommodity.orderNo.eq(form.getOrderNo()))
//                .where(qOrderCommodity.saleAfterStatus.notIn(
//                        SaleAfterStatusEnum.NONE,
//                        SaleAfterStatusEnum.COMPLETE,
//                        SaleAfterStatusEnum.CLOSE
//                ))
//                .fetchCount();
//        if (saleAfterCount > 0) {
//            return ResultDTO.failure("当前有商品的售后未完成");
//        }
//        QOrderEntity qOrder = QOrderEntity.orderEntity;
//        mallTransactionalService.newTransaction(() -> {
//            jpaQueryFactory.update(qOrder)
//                    .set(qOrder.settlementStatus, SettlementStatusEnum.WAIT_SETTLEMENT)
//                    .set(qOrder.orderStatus, OrderStatusEnum.FINISH)
//                    .set(qOrder.dealTime, LocalDateTime.now())
//                    .set(qOrder.reason, form.getReason().getReason(form.getReasonSlots()))
//                    .where(qOrder.orderNo.eq(form.getOrderNo()))
//                    .execute();
//        });
//
//        mallTransactionalService.newTransaction(() -> {
//            ResultDTO<Void> generateSettleOrderResult = settlementOrderService.generateRecord(form.getOrderNo(), LocalDateTime.now());
//            logger.info("订单完结后生成结算单结果orderNo={},result={}", form.getOrderNo(), generateSettleOrderResult);
//        });
//
//
//        OrderConfigEntity orderConfig = orderConfigRepository.findByOrderNo(form.getOrderNo());
//        if (orderConfig.getCheckType() == 2) {
//            //只有交易完结时需要结算的订单才需要将售后完成的负订单更新为可结算状态
//            mallTransactionalService.newTransaction(() -> {
//                //将订单关联的负订单更新到可结算状态
//                jpaQueryFactory.update(qOrder)
//                        .set(qOrder.settlementStatus, SettlementStatusEnum.WAIT_SETTLEMENT)
//                        .where(
//                                qOrder.orderStatus.eq(OrderStatusEnum.REFUND)
//                                        .and(qOrder.settlementStatus.eq(SettlementStatusEnum.UN_SETTLEMENT))
//                                        .and(qOrder.originalOrderNo.eq(form.getOrderNo()))
//                        ).execute();
//            });
//
//            OrderEntity order = form.getOrderEntity();
//            UpdateIncomeDistributionRecordBillableStatusForm updateIncomeDistributionRecordBillableStatusForm =
//                    new UpdateIncomeDistributionRecordBillableStatusForm();
//            updateIncomeDistributionRecordBillableStatusForm.setBillableTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//            updateIncomeDistributionRecordBillableStatusForm.setPayTime(order.getPayTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//            updateIncomeDistributionRecordBillableStatusForm.setOrderNo(order.getPaySerialNo());
//            rabbitTemplate.convertAndSend("ToSettlement", "UpdateIncomeDistributionRecordBillableStatusTopic", JSON.toJSONString(updateIncomeDistributionRecordBillableStatusForm));
//        }
//        CompletableFuture.runAsync(() -> {
//            logger.info("开始准备开具发票{}", form.getOrderNo());
//            ResultDTO<Void> invoiceResult = orderInvoiceService.makeOut(form.getOrderNo());
//            logger.info("订单完结后开具发票结果:{}", invoiceResult);
//        }, preOrderExecutor);
//
//        return ResultDTO.success();
//    }
//}
